﻿using Microsoft.EntityFrameworkCore;
using System.Text;
using System.Text.Json;
using System.Threading;
using 订单处理系统.Entity;
using 订单处理系统.Model;

namespace 订单处理系统.Hosted
{
    public class OrderConsumerHosted : BackgroundService
    {
        private readonly RabbitMQService _rabbitmqService;
        private readonly IServiceScopeFactory _scopeFactory;

        public OrderConsumerHosted(RabbitMQService rabbitmqService, IServiceScopeFactory scopeFactory)
        {
            _rabbitmqService = rabbitmqService;
            _scopeFactory = scopeFactory;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;
            var reciveTask = _rabbitmqService.ReceiveAsync("order:create", async (channel, body) =>
            {
                try
                {
                    //Console.WriteLine(JsonSerializer.Deserialize<string>(Encoding.UTF8.GetString(body)));
                    var order = JsonSerializer.Deserialize<Order>(Encoding.UTF8.GetString(body));
                    if (order == null) return;
                    using var scope = _scopeFactory.CreateScope();
                    var db = scope.ServiceProvider.GetRequiredService<OrderDbContext>();

                    var product = await db.Products.Where(p => p.Id == 2).FirstAsync();
                    product.Stock = product.Stock - 1;
                    db.Products.Update(product);
                    db.Orders.Add(order);
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("消费异常");
                }
                finally
                {
                    await channel.BasicAckAsync(deliveryTag: default, multiple: false, cancellationToken);
                }
            }, cancellationToken);
            return Task.CompletedTask;
        }
    }
}